﻿using System;
using System.Drawing;
using CamPlug.Api;
using System.Drawing.Imaging;

namespace CamPlug.StaticImage.Plugin
{
	public class StaticImagePlugin : IPlugin
	{
		public const string Name = "Static image";
		object SyncRoot = new object();
		Image Image;
		PropertiesForm PropertiesForm;

		string _fileName;
		public string FileName
		{
			get
			{
				lock (SyncRoot)
				{
					return _fileName;
				}
			}
			set
			{
				lock (SyncRoot)
				{
					_fileName = value;
					Image = null;
				}
			}
		}

		string IPlugin.Name
		{
			get { return Name; }
		}

		public void Clear()
		{
			FileName = null;
		}

		public Image GetImage()
		{
			lock (SyncRoot)
			{
				if (Image == null)
					return null;
				return (Image)Image.Clone();
			}
		}

		public byte[] SaveSettings()
		{
			return new byte[0];
		}

		public void LoadSettings(byte[] settings)
		{
		}

		public void UpdateBitmap(Bitmap bitmap)
		{
			lock (SyncRoot)
			{
				if (string.IsNullOrEmpty(FileName))
					return;

				if (Image == null)
					try
					{
						Image = Bitmap.FromFile(FileName);
					}
					catch 
					{
						Image = Properties.Resources.ImageError;
					}

				float xScale = bitmap.Width / Image.Width;
				float yScale = bitmap.Height / Image.Height;
				float scale = xScale < yScale ? xScale : yScale;
				float newWidth = Image.Width * scale;
				float newHeight = Image.Height * scale;
				float x = bitmap.Width / 2 - newWidth / 2;
				float y = bitmap.Height / 2 - newHeight / 2;

				var imageAttributes = new ImageAttributes();
				using (var canvas = Graphics.FromImage(bitmap))
				{
					canvas.DrawImage(Image, new RectangleF(x, y, newWidth, newHeight));
				}
			}
		}

		public void ShowPropertiesForm()
		{
			if (PropertiesForm == null)
				PropertiesForm = new PropertiesForm(this);
			if (!PropertiesForm.Visible)
				PropertiesForm.Show();
			PropertiesForm.BringToFront();
		}

		public void ShuttingDown()
		{
			lock (SyncRoot)
			{
				Image = null;
			}
		}
	}
}
